from flask import Blueprint, request, jsonify
from .. import db
from ..models import Category

categories_bp = Blueprint('categories', __name__)

@categories_bp.route('/add-category', methods=['POST'])
def add_category():
    data = request.get_json()
    required = ['user_id', 'name', 'type']
    if not all(data.get(field) for field in required):
        return jsonify({'error': '参数不完整'}), 400

    existing = Category.query.filter_by(user_id=data['user_id'], type=data['type'], name=data['name']).first()
    if existing:
        return jsonify({'error': '分类已存在'}), 400

    category = Category(user_id=data['user_id'], name=data['name'], type=data['type'], icon=data.get('icon', ''), color=data.get('color', ''))
    db.session.add(category)
    db.session.commit()
    return jsonify({'message': '分类添加成功'})

@categories_bp.route('/get-categories', methods=['POST'])
def get_categories():
    data = request.get_json()
    user_id = data.get('user_id')
    type = data.get('type')

    if not user_id or not type:
        return jsonify({'error': '缺少参数'}), 400

    categories = Category.query.filter_by(user_id=user_id, type=type).all()
    result = [{
        'id': c.id,
        'name': c.name,
        'icon': c.icon,
        'color': c.color,
        'type': c.type
    } for c in categories]
    return jsonify({'categories': result})

@categories_bp.route('/update-category', methods=['PUT'])
def update_category():
    data = request.get_json()
    category = Category.query.filter_by(id=data.get('id'), user_id=data.get('user_id')).first()
    if not category:
        return jsonify({'error': '分类不存在'}), 404

    category.name = data.get('name')
    category.icon = data.get('icon')
    category.color = data.get('color')
    category.type = data.get('type')

    db.session.commit()
    return jsonify({'message': '分类更新成功'})

@categories_bp.route('/delete-category', methods=['DELETE'])
def delete_category():
    data = request.get_json()
    category = Category.query.filter_by(id=data.get('id'), user_id=data.get('user_id')).first()
    if not category:
        return jsonify({'error': '分类不存在或无权限'}), 404

    db.session.delete(category)
    db.session.commit()
    return jsonify({'message': '分类删除成功'})
